﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Web;
using System.IO;
using System.Xml;

namespace ConsoleApplication1
{
    public class GoogleMapHelper
    {
        static string geocodeUrlFormat = "http://maps.google.com/maps/api/geocode/xml?address={0}&sensor=false";

        public static string GetLatLngByAddress(string add)
        {
            string url = string.Format(geocodeUrlFormat, HttpUtility.UrlEncode(add.ToString()));
            WebRequest request = WebRequest.Create(url);
            using (Stream stream = request.GetResponse().GetResponseStream())
            {
                using (StreamReader reader = new StreamReader(stream))
                {
                    string result = reader.ReadToEnd();
                    XmlDocument xml = new XmlDocument();
                    xml.LoadXml(result);

                    if (xml.SelectSingleNode("/GeocodeResponse/status").InnerText == "OK")
                    {
                        var lat = double.Parse(xml.SelectSingleNode("/GeocodeResponse/result/geometry/location/lat").InnerText);
                        var lng = double.Parse(xml.SelectSingleNode("/GeocodeResponse/result/geometry/location/lng").InnerText);

                        return string.Format("{0},{1}", lat,lng);
                    }

                    return string.Empty;
                }
            }
        }
    }
}
